<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ActiveAddFriendRobotMapper;
use App\CustHub\Model\ChAddFriendRobotLog;
use App\CustHub\Model\ChRobot;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\MineCollection;
use Mine\MineModel;
use Mine\MineResponse;
use function Hyperf\Collection\data_get;

class ActiveAddFriendRobotService extends AbstractService
{
    #[Inject]
    protected ChRobot $robot;

    #[Inject]
    protected ChAddFriendRobotLog $log;

    public $mapper;

    public function __construct(ActiveAddFriendRobotMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function robotList($params): array
    {
        $pageSize = $params['page_size'] ?? MineModel::PAGE_SIZE;
        $uid = $params['uid'];
        $groupId = $params['group_id'] ?? null;
        $search = $params['search'] ?? '';
        $status = $params['status'] ?? null;
        $loginStatus = $params['login_status'] ?? null;

        $query = $this->mapper->model::query()
            ->leftJoin('ch_robot', 'ch_add_friend_robot.robot_id', '=', 'ch_robot.id')
            ->leftJoin('ch_add_friend_group', 'ch_add_friend_robot.group_id', '=', 'ch_add_friend_group.id')
            ->select([
                'ch_add_friend_robot.id',
                'ch_add_friend_robot.group_id',
                'ch_add_friend_robot.robot_id',
                'ch_robot.nickname',
                'ch_robot.avatar',
                'ch_robot.login_status',
                'ch_add_friend_group.group_name',
                'ch_robot.corp_name'
            ])
            ->where('ch_add_friend_robot.uid', $uid)
            ->orderBy('ch_add_friend_robot.id', 'desc');

        if ($groupId !== null) {
            $query->addSelect([
                'ch_add_friend_robot.status',
                'ch_add_friend_robot.hello_time',
                'ch_add_friend_robot.max_time',
            ])->where('ch_add_friend_robot.group_id', $groupId);

            if (!empty($status)) {
                $query->where('ch_add_friend_robot.status', $status);
            }

            if (!empty($loginStatus)) {
                $query->where('ch_robot.login_status', $loginStatus);
            }
            if (!empty($search)) {
                $query->where('ch_robot.nickname', 'like', "%$search%");
            }
        } else {

            if (!empty($search)) {
                $query->where(function ($q) use ($search) {
                    $q->where('ch_robot.corp_name', 'like', "%$search%")
                        ->orWhere('ch_robot.nickname', 'like', "%$search%");
                });
            }
        }

        $paginate = $query->paginate((int)$pageSize);
        return $this->mapper->setPaginate($paginate);
    }

    public function getNewRobot($params): void
    {
        $robotIds= explode(',', $params['robot_id']);
        $groupId = (int)$params['group_id'];
        $max_time = data_get($params, 'max_time', 0);
        foreach ($robotIds as $robotId){
            $condition=[
                'main_uid' => $params['main_uid'],
                'uid' => $params['uid'],
                'robot_id' => $robotId,
                'group_id' => $groupId,
            ];

            $data =  ['max_time'=>$max_time];
            $this->mapper->model::updateOrCreate($condition,$data);
        }
    }

    public function deleteRobot($id): bool
    {
        return $this->delete((array)$id);
    }


    public function delWechat($params): bool
    {
        $ids = is_array($params['ids']) ? $params['ids'] : explode(',', $params['ids']);
        $this->mapper->model::whereIn('id', $ids)->delete();
        return true;
    }

    public function setWechat($params): bool
    {
        $ids = is_array($params['ids']) ? $params['ids'] : explode(',', $params['ids']);
        $dateTime = date('Y-m-d H:i:s', time());

        $fillFields = (new $this->mapper->model)->getFillable();
        $updateData = array_intersect_key($params, array_flip($fillFields));

        $logEntries = [];
        if (isset($updateData['status'])) {
            $logContent = $updateData['status'] == 1 ? '手动启用' : '手动停用';

            $robotData = $this->log::whereIn('id', $ids)
                ->get(['id', 'uid', 'main_uid', 'ask_robot_id']);

            $logEntries = $robotData->map(fn($robot) => [
                'uid'         => $robot->uid,
                'main_uid'    => $robot->main_uid,
                'ask_robot_id' => $robot->ask_robot_id,
                'created_at'  => $dateTime,
                'content'     => $logContent
            ])->toArray();
        }

        if (!empty($logEntries)) {
            $this->log->insert($logEntries);
        }

        if (!empty($updateData)) {
            $this->mapper->model::whereIn('id', $ids)->update($updateData);
        }

        return true;
    }

    public function getRobotLog($params)
    {
        return $this->log::query()
            ->select(['id','content','created_at'])
            ->where('uid', $params['uid'])
            ->where('ask_robot_id', $params['robot_id'])
            ->orderBy('created_at', 'desc')
            ->get();
    }

    public function robotData(array $params)
    {

        $pageSize = (int)($params['page_size']?? MineModel::PAGE_SIZE);


        $query = $this->mapper->robotData($params);

        $list = $query->paginate($pageSize);

        return $this->mapper->setPaginate($list);
    }

    public function exportRobotData(array $params, string $dto)
    {
        if (empty($dto)) {
            return container()->get(MineResponse::class)->error('导出未指定DTO');
        }

        if (empty($filename)) {
            $filename = "主动加好友-分号数据" . Carbon::now()->format('Y-m-d_H-i-s') . ".xlsx";
        }

        // 调用 robotData 方法获取数据
        $query = $this->mapper->robotData($params);

        $list = $query->get();
        // 数据转换
        $list->transform(function ($item) {
            return [
                'nickname' => $item->nickname,
                'corp_name' => $item->corp_name,
                'total_greetings' => $item->total_greetings,
                'passed_friends' => $item->passed_friends,
                'pass_rate' => $item->pass_rate . '%', // 转换为百分比格式
                'not_found_wechat' => $item->not_found_wechat,
            ];
        });

        // 执行导出
        return (new MineCollection())->export($dto, $filename, $list->toArray());
    }
}